<template>
  <div class="addBrand-container">
    <div class="container">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        :inline="true"
        label-width="180px"
        class="demo-ruleForm"
      >
        <div>
          <el-form-item label="材料名称:" prop="name">
            <el-input
              v-model="ruleForm.name"
              placeholder="请填写材料名称"
              maxlength="14"
            />
          </el-form-item>
          <!-- <el-form-item label="材料分类:" prop="idType">
            <el-select
              v-model="ruleForm.idType"
              placeholder="请选择材料分类"
              @change="$forceUpdate()"
            >
              <el-option
                v-for="(item, index) in setMealList"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item> -->
        </div>
        <div>
          <el-form-item label="材料价格:" prop="price">
            <el-input v-model="ruleForm.price" placeholder="请设置材料价格" />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="默认价格:" prop="defaultPrice">
            <el-input
              v-model="ruleForm.defaultPrice"
              placeholder="请输入默认价格"
            />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="默认数量:" prop="defaultNumber">
            <el-input
              v-model="ruleForm.defaultNumber"
              placeholder="请输入默认数量"
            />
          </el-form-item>
        </div>
        <!-- <div>
          <el-form-item label="默认数量:" prop="defaultNumber">
            <el-input
              v-model="ruleForm.defaultNumber"
              placeholder="请输入默认数量"
            />
          </el-form-item>
        </div> -->
        <div>
          <el-form-item label="单位:" prop="unit">
            <el-input v-model="ruleForm.unit" placeholder="请设置单位" />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="范围:" prop="range">
            <el-input v-model="ruleForm.range" placeholder="请设置范围" />
          </el-form-item>
        </div>
        <!-- <div>
          <el-form-item label="售卖状态:" prop="status">
            <el-switch
              v-model="ruleForm.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="售卖中"
              inactive-text="已下架"
            />
          </el-form-item>
        </div> -->
        <div>
          <el-form-item label="材料图片:" required prop="image">
            <image-upload :prop-image-url="imageUrl" @imageChange="imageChange">
              图片大小不超过2M<br />仅能上传 PNG JPEG JPG类型图片<br />建议上传200*200或300*300尺寸的图片
            </image-upload>
          </el-form-item>
        </div>
        <div class="address">
          <el-form-item label="材料描述:">
            <el-input
              v-model="ruleForm.description"
              type="textarea"
              :rows="3"
              maxlength="200"
              placeholder="材料描述，最长200字"
            />
          </el-form-item>
        </div>
        <div class="subBox address">
          <el-form-item>
            <el-button @click="$router.back()">取消</el-button>
            <el-button
              type="primary"
              :class="{ continue: actionType === 'add' }"
              @click="submitForm('ruleForm', false)"
            >
              保存
            </el-button>
            <el-button
              v-if="actionType == 'add'"
              type="primary"
              @click="submitForm('ruleForm', true)"
            >
              保存并继续添加
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import HeadLable from '@/components/HeadLable/index.vue'
import ImageUpload from '@/components/ImgUpload/index.vue'
import AddDish from './components/AddDish.vue'
import { querySetmealById, addSetmeal, editSetmeal } from '@/api/setMeal'
import { getCategoryList } from '@/api/dish'
import { baseUrl } from '@/config.json'

@Component({
  name: 'addShop',
  components: {
    HeadLable,
    AddDish,
    ImageUpload,
  },
})
export default class extends Vue {
  private value: string = ''
  private setMealList: [] = []
  private seachKey: string = ''
  private dishList: [] = []
  private imageUrl: string = ''
  private actionType: string = ''
  private dishTable: [] = []
  private dialogVisible: boolean = false
  private checkList: any[] = []
  private ruleForm = {
    name: '',
    categoryId: '',
    range: '',
    price: '',
    code: '',
    image: '',
    description: '',
    // status: true,
    unit: '',
    defaultNumber: '',
    // idType: '',
    // defaultPrice: '',
  }

  get rules() {
    return {
      name: {
        required: true,
        validator: (rule: any, value: string, callback: Function) => {
          if (!value) {
            callback(new Error('请输入材料名称'))
          } else {
            const reg = /^([A-Za-z0-9\u4e00-\u9fa5]){2,20}$/
            if (!reg.test(value)) {
              callback(new Error('材料名称输入不符，请输入2-20个字符'))
            } else {
              callback()
            }
          }
        },
        trigger: 'blur',
      },
      idType: {
        required: true,
        message: '请选择材料分类',
        trigger: 'change',
      },
      image: {
        required: true,
        message: '菜品图片不能为空',
      },
      price: {
        required: true,
        // 'message': '请输入材料价格',
        validator: (rules: any, value: string, callback: Function) => {
          const reg = /^([1-9]\d{0,5}|0)(\.\d{1,2})?$/
          if (!reg.test(value) || Number(value) <= 0) {
            callback(
              new Error(
                '材料价格格式有误，请输入大于零且最多保留两位小数的金额'
              )
            )
          } else {
            callback()
          }
        },
        trigger: 'blur',
      },
      code: { required: true, message: '请输入商品码', trigger: 'blur' },
    }
  }

  created() {
    this.getDishTypeList()
    this.actionType = this.$route.query.id ? 'edit' : 'add'
    if (this.actionType == 'edit') {
      this.init()
    }
  }

  private async init() {
    querySetmealById(this.$route.query.id).then((res) => {
      if (res && res.data && res.data.code === 1) {
        this.ruleForm = res.data.data
        // this.ruleForm.status = res.data.data.status == '1'
        // ;(this.ruleForm as any).price = res.data.data.price
        // this.imageUrl = `http://172.17.2.120:8080/common/download?name=${res.data.data.image}`
        this.imageUrl = res.data.data.image
        this.checkList = res.data.data.setmealDishes
        this.dishTable = res.data.data.setmealDishes.reverse()
        // this.ruleForm.idType = res.data.data.categoryId
      } else {
        this.$message.error(res.data.msg)
      }
    })
  }
  private seachHandle() {
    this.seachKey = this.value
  }
  // 获取菜品分类
  private getDishTypeList() {
    getCategoryList({ type: 2, page: 1, pageSize: 1000 }).then((res) => {
      if (res && res.data && res.data.code === 1) {
        this.setMealList = res.data.data.map((obj: any) => ({
          ...obj,
          idType: obj.id,
        }))
      } else {
        this.$message.error(res.data.msg)
      }
    })
  }
  // 删除材料
  delDishHandle(index: any) {
    this.dishTable.splice(index, 1)
    this.checkList = this.dishTable
    // this.checkList.splice(index, 1)
  }
  // 获取添加菜品数据 - 确定加菜倒序展示
  private getCheckList(value: any) {
    this.checkList = [...value].reverse()
  }

  // 添加菜品
  openAddDish(st: string) {
    this.seachKey = ''
    this.dialogVisible = true
  }
  // 取消添加菜品
  handleClose(done: any) {
    // this.$refs.adddish.close()
    this.dialogVisible = false
    this.checkList = JSON.parse(JSON.stringify(this.dishTable))
    // this.dialogVisible = false
  }

  // 保存添加菜品列表
  public addTableList() {
    this.dishTable = JSON.parse(JSON.stringify(this.checkList))
    this.dishTable.forEach((n: any) => {
      n.copies = 1
    })
    this.dialogVisible = false
  }

  public submitForm(formName: any, st: any) {
    if (!this.ruleForm.image) return this.$message.error('材料图片不能为空')

    // 将价格字段转换为数字类型
    this.ruleForm.price = parseFloat(this.ruleForm.price)
    this.ruleForm.defaultPrice = parseFloat(this.ruleForm.defaultPrice)
    this.ruleForm.defaultNumber = parseFloat(this.ruleForm.defaultNumber)
    // this.ruleForm.unit = parseFloat(this.ruleForm.unit)
    // this.ruleForm.unit = this.ruleForm.unit

    // this.ruleForm.defaultNumber = parseFloat(this.ruleForm.defaultNumber)
    let prams = { ...this.ruleForm } as any
    // ;(prams as any).status =
    //   this.actionType === 'add' ? 0 : this.ruleForm.status ? 1 : 0
    // prams.categoryId = this.ruleForm.idType

    if (this.actionType == 'add') {
      delete prams.id
      addSetmeal(prams)
        .then((res) => {
          if (res && res.data && res.data.code === 1) {
            this.$message.success('材料添加成功！')
            if (!st) {
              this.$router.push({ path: '/setmeal' })
            } else {
              ;(this as any).$refs.ruleForm.resetFields()
              this.ruleForm = {
                name: '',
                categoryId: '',
                range: '',
                price: '',
                code: '',
                image: '',
                description: '',
                defaultPrice: '',
                // status: true,
                defaultNumber: '',
                // id: '',
                unit: '',
                // idType: '',
              } as any
              this.imageUrl = ''
            }
          } else {
            this.$message.error(res.data.msg)
          }
        })
        .catch((err) => {
          this.$message.error('请求出错了：' + err.message)
        })
    } else {
      delete prams.updateTime
      editSetmeal(prams)
        .then((res) => {
          if (res.data.code === 1) {
            this.$message.success('材料修改成功！')
            this.$router.push({ path: '/setmeal' })
          } else {
            // this.$message.error(res.data.desc || res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error('请求出错了：' + err.message)
        })
    }
  }

  imageChange(value: any) {
    this.ruleForm.image = value
  }
}
</script>
<style>
.avatar-uploader .el-icon-plus:after {
  position: absolute;
  display: inline-block;
  content: ' ' !important;
  left: calc(50% - 20px);
  top: calc(50% - 40px);
  width: 40px;
  height: 40px;
  background: url('./../../assets/icons/icon_upload@2x.png') center center
    no-repeat;
  background-size: 20px;
}
</style>
<style lang="scss">
// .el-form-item__error {
//   top: 90%;
// }
.addBrand-container {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #333333;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 160px;
    line-height: 160px;
    text-align: center;
  }

  .avatar {
    width: 200px;
    height: 160px;
    display: block;
  }

  // .el-form--inline .el-form-item__content {
  //   width: 293px;
  // }

  .el-input {
    width: 293px;
  }

  .address {
    .el-form-item__content {
      width: 777px !important;
    }
  }

  .el-input__prefix {
    top: 2px;
  }

  .addDish {
    .el-input {
      width: 130px;
    }

    .el-input-number__increase {
      border-left: solid 1px #fbe396;
      background: #fffbf0;
    }

    .el-input-number__decrease {
      border-right: solid 1px #fbe396;
      background: #fffbf0;
    }

    input {
      border: 1px solid #fbe396;
    }

    .table {
      border: solid 1px #ebeef5;
      border-radius: 3px;

      th {
        padding: 5px 0;
      }

      td {
        padding: 7px 0;
      }
    }
  }

  .addDishList {
    .seachDish {
      position: absolute;
      top: 12px;
      right: 20px;
    }

    .el-dialog__footer {
      padding-top: 27px;
    }

    .el-dialog__body {
      padding: 0;
      border-bottom: solid 1px #efefef;
    }

    .seachDish {
      .el-input__inner {
        height: 40px;
        line-height: 40px;
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.addBrand {
  &-container {
    margin: 30px;

    .container {
      position: relative;
      z-index: 1;
      background: #fff;
      padding: 30px;
      border-radius: 4px;
      min-height: 500px;

      .subBox {
        padding-top: 30px;
        text-align: center;
        border-top: solid 1px $gray-5;
      }

      .el-input {
        width: 350px;
      }

      .addDish {
        width: 777px;

        .addBut {
          background: #ffc200;
          display: inline-block;
          padding: 0px 20px;
          border-radius: 3px;
          line-height: 40px;
          cursor: pointer;
          border-radius: 4px;
          color: #333333;
          font-weight: 500;
        }

        .content {
          background: #fafafb;
          padding: 20px;
          border: solid 1px #d8dde3;
          border-radius: 3px;
        }
      }
    }
  }
}
</style>
